package com.greenline.push.home.controllers.message;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.greenline.guser.annotation.GuserResource;
import com.greenline.push.common.json.BaseJson;
import com.greenline.push.common.json.GridJsonData;
import com.greenline.push.core.enums.ClassMessageStatus;
import com.greenline.push.core.pushcenter.ClassMessageManager;
import com.greenline.push.core.pushcenter.MsgForSendManager;
import com.greenline.push.dal.pushcenter.dataobject.ClassMessageDO;
import com.greenline.push.dal.query.ClassMessageQuery;
import com.greenline.push.services.PushCenterCommonService;
import com.greenline.push.services.dto.ResponseDTO;

@Controller
@RequestMapping(value = "/classmsg")
public class MsgClassController extends SimpleFormController {

    @Resource
    private ClassMessageManager msgManager;
    @Resource
    private MsgForSendManager msgForSendManager;
    @Resource
    private PushCenterCommonService commonService;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
        binder.registerCustomEditor(Date.class, dateEditor);
        super.initBinder(request, binder);
    }

    @RequestMapping(value = "/sending/query", method = RequestMethod.GET)
    public String querySendingRecord(ModelMap model) {
        return "msgclass/sending_list";
    }

    @RequestMapping(value = "/sent/query", method = RequestMethod.GET)
    public String querySentRecord(ModelMap model) {
        return "msgclass/sent_list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addMsgClass(ModelMap model) {
        return "msgclass/msgclass_add";
    }

    @RequestMapping("/sendingquery.json")
    @ResponseBody
    public GridJsonData<ClassMessageDO> listSendingList(ClassMessageQuery query,
            @RequestParam(value = "page", defaultValue = "1", required = false) String pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) String pageSize) {
        query.setPageIndex(Integer.parseInt(pageIndex));
        query.setPageSize(Integer.parseInt(pageSize));
        query.setStatus(ClassMessageStatus.WAIT_PUSH.getStatus());
        GridJsonData<ClassMessageDO> ret = new GridJsonData<ClassMessageDO>();
        ret.setQuery(msgManager.listByQuery(query));
        return ret;
    }

    @RequestMapping("/sentquery.json")
    @ResponseBody
    public GridJsonData<ClassMessageDO> listSentList(ClassMessageQuery query,
            @RequestParam(value = "page", defaultValue = "1", required = false) String pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) String pageSize) {
        query.setPageIndex(Integer.parseInt(pageIndex));
        query.setPageSize(Integer.parseInt(pageSize));
        query.setStatus(ClassMessageStatus.PUSHED.getStatus());
        GridJsonData<ClassMessageDO> ret = new GridJsonData<ClassMessageDO>();
        ret.setQuery(msgManager.listByQuery(query));
        return ret;
    }

    // @GuserResource("广播消息添加")
    // @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    // public @ResponseBody ModelAndView add(ModelMap model,
    // @ModelAttribute("classmsg") ClassMessageDO msgDO) {
    // ModelAndView view = new ModelAndView("/msgclass/sending_list");
    // try {
    // if (msgManager.insert(msgDO) > 0) {
    // view.addObject("result", "插入成功");
    // view.addObject("issucc", true);
    // return view;
    // } else {
    // view.addObject("result", "插入失败");
    // view.addObject("issucc", false);
    // return view;
    // }
    // } catch (Exception e) {
    // view.addObject("result", "插入错误");
    // view.addObject("issucc", false);
    // return view;
    // }
    // }

    @GuserResource("广播消息添加")
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson add2(ModelMap model, HttpServletRequest request, String classCode, String domainCode, String templateCode, Date sendingTime) {
        BaseJson json = new BaseJson();
        try {
            if (StringUtils.isBlank(classCode)) {
                json.setHasError(true);
                json.setMessage("提交出错组编号不可为空");
                return json;
            }
            if (StringUtils.isBlank(domainCode)) {
                json.setHasError(true);
                json.setMessage("提交出错域编号不可为空");
                return json;
            }
            if (StringUtils.isBlank(templateCode)) {
                json.setHasError(true);
                json.setMessage("提交出错模版编号不可为空");
                return json;
            }
            Map<String, String> map = new HashMap<String, String>();
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (paramValue.length() != 0) {
                        map.put(paramName, paramValue);
                    }
                }
            }
            // remove not need params
            map.remove("classCode");
            map.remove("domainCode");
            map.remove("templateCode");

            Long d = (sendingTime == null )? null : sendingTime.getTime();
            // call remote
            ResponseDTO<Boolean> response = commonService.createBroadCast(classCode, templateCode, domainCode, map, d);
            boolean result = response.getDataResult();
            if (result) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错" + response.getMessage() + response.getErrorMsg());
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错" + e.getMessage());
            logger.error(json.getMessage(), e);
        }
        return json;
    }
}
